package com.juyu.miliao.api.dao.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.mysql.VipDao;
import com.juyu.miliao.api.domain.Vip;
import com.juyu.miliao.common.constant.VipRedisKey;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 */
@Repository
public class VipRedisDao {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private VipDao vipDao;

    @Autowired
    private ObjectMapper objectMapper;

    public Vip getVipInfoById(int vipId) throws IOException {
        String key = VipRedisKey.getVipRedisKey(vipId);
        String target = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(target)){
            return objectMapper.readValue(target, Vip.class);
        }else{
            Vip vip = vipDao.getVipById(vipId);
            if(vip!=null){
                stringRedisTemplate.opsForValue().set(key,objectMapper.writeValueAsString(vip),10, TimeUnit.MINUTES);
            }
            return vip;
        }
    }


}
